package com.kongwg.java1;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author kongwg
 * @create 2020-12-12 10:48
 */
public class TreeTest {


    @Test
    public void test(){
        TreeSet set = new TreeSet();
//
//        set.add(12);
//        set.add(23);
//        set.add(-98);
//        set.add(25);
//        set.add(1342);
//        set.add(16);
//        set.add(18);

        set.add(new User("Tom",12));
        set.add(new User("Jerry",32));
        set.add(new User("Jim",2));
        set.add(new User("Mike",65));
        set.add(new User("Jack",33));
        set.add(new User("Jack",56));
        set.add(new User("Jack",57));

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }

    @Test
    public void test2(){
        Comparator com = new Comparator() {

            //按学生的年龄排序
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User && o2 instanceof User){
                    User user1 = (User) o1;
                    User user2 = (User) o2;


                    return Integer.compare(user1.getAge(),user2.getAge());
                }
                throw  new RuntimeException("输入的类型不是user");
            }


        };

        Set set = new TreeSet(com);

        set.add(new User("Tom",12));
        set.add(new User("Jerry",32));
        set.add(new User("Jim",2));
        set.add(new User("Mike",65));
        set.add(new User("Jack",33));
        set.add(new User("Jack",56));
        set.add(new User("Jack",57));


        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}
